import QtQuick
import EcgModel 1.0

// 定义折线图组件
Canvas {
    id: chartCanvas
    width: parent.width
    height: parent.height
    property int start
    property list<int> padding : [0,0,0,0]
    property real canvasGain : 1.0 //画图增益
    property bool displayOneLead : false
    property int duration: 16000 //持续时长毫秒

    onPaint: {
        const paddingTop = padding[0],
        paddingRight = padding[1],
        paddingBottom = padding[2],
        paddingLeft = padding[3]

        const adcZero = EcgModel.adcZero
        const adcGain = EcgModel.adcGain
        const canvasHeight = height - paddingTop - paddingBottom;
        const canvasWidth = width - paddingLeft - paddingRight
        let data = EcgsignalModel.getEcgSignalFragment(start>=0?start:0,duration);
        // console.log(data)
        if(displayOneLead) data = [data[0]];
        const yRange = canvasWidth / (duration / 1000 * 5) * 2 //每毫伏所占高度

        const ctx = getContext("2d");
        ctx.clearRect(0, 0, width, height);
        ctx.strokeStyle = "#666666";
        ctx.lineWidth = 1;
        ctx.beginPath();

        const numberLeads = data.length
        for(var i = 0; i < numberLeads; i++){
            var xStep = canvasWidth / (data[i].length - 1);
            for(var j = 0; j< data[i].length; j++){
                var ecgData = (data[i][j] - adcZero) / adcGain * canvasGain
                var x = paddingRight + j * xStep;
                var y = paddingTop + -1 * ecgData * yRange + (i+0.5) * canvasHeight / numberLeads
                if (j === 0) {
                    ctx.moveTo(x, y);
                } else {
                    ctx.lineTo(x, y);
                }
            }
        }

        ctx.stroke();
    }
    // 监听数据变化，重新绘制
    Connections {
        target: chartCanvas
        function onStartChanged() {
            chartCanvas.requestPaint();
        }
    }
}
